import { ActionTree, Module, MutationTree } from "vuex";
import { Login, getUserInfo } from '@/api/base'
import { setToken, removeToken } from "@/utils/auth";
import { IRootState } from "../index";
import router, { asyncRoutes, constantRoutes } from '@/route/index'
import { RouteRecordRaw } from "vue-router";
// 定义user的state类型
export interface UserState {
  token: string,
  username: string,
  password: string,
  routes: Array<RouteRecordRaw>,
  // addRoutes: Array<any>,
  permission: Array<string>,
  menuPermission: boolean
}

const mutations: MutationTree<UserState> = {
  SET_TOKEN(state, token: string) {
    removeToken();
    setToken(token)
    state.token = token;

  },
  SET_USER_INFO(state, userInfo) {
    state.username = userInfo.username;
    state.permission = userInfo.permission
  },
  // SET_ROUTES(state, addRoutes) {
  //   state.addRoutes = addRoutes
  // }
  SET_MENU_PERMISSION(state, has) {
    state.menuPermission = has;
  }
}

const actions: ActionTree<UserState, IRootState> = {
  async login({ commit }, data) {
    try {
      const res = await Login(data);
      if (res.data.code != 0) throw new Error(res.data.message);
      commit('SET_TOKEN', res.data.data.token)
      return Promise.resolve(res.data)
    } catch (err) {
      commit('SET_TOKEN', '');
      return Promise.reject(err)
    }
  },
  async getUserInfo({ commit, state }) {
    try {
      const res = await getUserInfo(state.token);
      if (res.data.code != 0) return Promise.reject(new Error('用户信息获取失败'));
      const userInfo = res.data.data;
      commit('SET_USER_INFO', userInfo);
      return Promise.resolve(userInfo)
    } catch (err) {
      return Promise.reject(err);
    }
  },
  async setRoute({ commit, state }) {
    try {
      const permission = state.permission;
      let addRoutes = filterAsyncRouter(asyncRoutes, permission);
      // router.addRoutes()
      for (let x of addRoutes) {
        router.addRoute(x);
        state.routes.push(x)
      }
      // 不需要在store中存储异步路由列表和全部路由列表，没什么用
      // commit('SET_ROUTES', addRoutes)
      commit('SET_MENU_PERMISSION', true)
      return Promise.resolve(addRoutes)
    } catch (err) {
      return Promise.reject(err)
    }
  }

}

function filterAsyncRouter(asyncRoutes: RouteRecordRaw[], permission: string[]) {
  // 动态添加的路由，要根据权限过滤过滤出可用的路由
  const accessedRouters = asyncRoutes.filter(route => {
    if (hasPermission(permission, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permission);
      }
      return true;
    }
    return false;
  });
  return accessedRouters;
}
function hasPermission(permission: string[], route: RouteRecordRaw) {
  if (route.meta && route.meta.sign) {
    return permission.indexOf(route.meta.sign) != -1;
  } else {
    return true; // 没有配置meta，默认都有权限
  }
}
const user: Module<UserState, IRootState> = {
  // 
  namespaced: true,
  state: {
    token: '',
    username: '',
    permission: [],
    password: '',
    routes: constantRoutes,
    // addRoutes: [],
    menuPermission: false
  },
  mutations,
  actions
}

export default user